<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/mobile/include/taglib.jsp"%>
<html>
<head>
	<title>${activity.name }</title>
	<%@include file="/WEB-INF/views/mobile/include/head.jsp" %>
	<link href="${ctxFront}/css/business.css" type="text/css" rel="stylesheet" />
	<link href="${ctxFront}/css/slideTab.css" type="text/css" rel="stylesheet" />
	<script type="text/javascript"> 
	var appId = '${appId}';
	var sid="${merchant.id}";
	var mobile="${mobile}";
	var totalNumber = ${totalNumber};
	var totalAmount = ${totalAmount};
	var len = ${fn:length(activity.timeList)};
	var timeNum = ${timeNum};
	var winWidth = $(window).width();
	var winHeight = $(window).height();
	$(".TabContent").width(winWidth);
	//$(".AllTabs").width(len*winWidth);
	$(".ui-page").height(winHeight-50);
	$(document).ready(function() {
		//处理tabMenu显示
		initTabMenuText();
	});
	function initTabMenuText(){
		$(".tab-title").each(function(index){
			if(index==timeNum){
				$(".tab-time:eq("+index+")").css("font-size", "18px").css("font-weight","blod");
			}else{
				$(".tab-time:eq("+index+")").css("font-size", "16px").css("font-weight", "normal");
			}
		});
	}
	function setTabMenuText(){
		$(".tab-title").each(function(index){
			if(index==timeNum){
				$(".tab-time:eq("+index+")").css("font-size", "18px").css("font-weight","blod");
			}else{
				$(".tab-time:eq("+index+")").css("font-size", "16px").css("font-weight", "normal");
			}
		});
	}
	function doBuyProduct(obj){
		if($(obj).attr("status")=="0") return;
		//判断是否登录
		if(!checkLogin()) return;
		
		var param = "sid="+sid+"&mobile="+mobile+"&productId="+$(obj).parent().parent().attr("id")+"&actProductId="+$(obj).parent().parent().find("input[id='actProductId']").val()+"&price="+$(obj).parent().parent().find("input[id='price']").val()+"&cartId="+$(obj).parent().parent().find("input[id='cartId']").val();
		loading('正在提交，请稍等...');
		//异步去抢购
		$.ajax({
			type: 'get',
			url: '${ctxShop}/business/activity/panicBuy',
			data: param,
			dataType: 'json',
			success: function(data){
				hideLoader();
				if(data.status==200){ //抢购成功
					var mess = data.message;
					var cartId = mess.split("_")[0];
					$(obj).parent().parent().find("input[id='buyState']").val(1);
					$(obj).parent().parent().find("input[id='cartId']").val(cartId);
					var number = $(obj).parent().parent().find("input[id='buyNumber']").val();
					var buyNumber = parseInt(mess.split("_")[1]);
					$(obj).parent().parent().find("input[id='buyNumber']").val(buyNumber);
					var bl =  (Math.round(buyNumber / number * 10000) / 100.00 + "%");
					$(this).parent().parent().find(".buy-desc").text("已抢购"+bl).css("color", "#bbb");
					$(obj).attr("status", 0);
	        		$(obj).attr("src", "${ctxFront }/images/business/btn_5.png");
					//openPopup(mess.split("_")[2]);
					//closePopup(3000);
					//执行购买数量和金额计算
					var productPrice = parseFloat($(obj).parent().parent().find("input[id='price']").val());
					totalNumber += 1;
					totalAmount = parseFloat(totalAmount)+(1 * productPrice);
					totalAmount = changeTwoDecimal_f(totalAmount);
					$(".totalAmount strong").text("￥"+totalAmount);
					if($(".totalNumber")){
						if($(".totalNumber-badger").is(":hidden")){
							$(".totalNumber-badger").show();
						}
						$(".totalNumber").text(totalNumber);
					}
					if(appId!="" && appId!=null){
						document.location="ievent://getShoppingCartCount";
					}
				}else if(data.status==400){ //抢光了
					$(obj).attr("status", 0);
	        		$(obj).attr("src", "${ctxFront }/images/business/btn_2.png");
	        		openPopup(data.message);
					closePopup(2000);
				}else{
					openPopup(data.message);
					closePopup(2000);
				}
			},
			failure: function(){
				openPopup("操作失败");
				closePopup(2000);
			}				
		});
	}
	</script>
	<script type="text/javascript"> 
		$(document).ready(function() {
			//预加载图片
			startLoadImage();
		});
		function startLoadImage(){
			$(".displayImages").each(function(index){
				loadImage($(this).attr("id"),$(this).attr("path"),loadResult);
			});
		}
	</script>
	<script type="text/javascript">
		$(document).ready(function(){
			$(".container .TabMenu .allMenu").width(len*70+len*8);
			//Set the selector in the first tab
			$(".container .TabMenu .allMenu span:eq("+timeNum+")").addClass("selector");
			//控制滚动条移动位置
			var container = $('.container .TabMenu'),
				scrollTo = $('.container .TabMenu .allMenu span:eq('+timeNum+')');
			
			container.scrollLeft(
			    scrollTo.offset().left - container.offset().left + container.scrollLeft()
			);
			
			// Or you can animate the scrolling:
			container.animate({
			    scrollLeft: scrollTo.offset().left - container.offset().left + container.scrollLeft()
			});
			
			//Add click action to tab menu
			$(".container .TabMenu .allMenu span").on('click', function(){  
            	var index = $(".container .TabMenu .allMenu span").index(this);
				if(index!=timeNum){
					timeNum = index;
					clearInterval(timer);
					selectTabMenu(index);
				}
            });
		});
		function selectTabMenu(index){
			var obj = $(".container .TabMenu .allMenu span:eq("+index+")");
			//Remove the exist selector
			$(".selector").removeClass("selector");
			//Add the selector class to the sender
			$(obj).removeClass("hovering");
			$(obj).addClass("selector");
			//设置tabMenu菜单内容样式
			setTabMenuText();
			var timeId = $("input[id='timeId']:eq("+index+")").val();
			loading('正在加载，请稍等...');
			//异步去抢购
			$.ajax({
				type: 'post',
				url: '${ctxShop}/business/activity/getActivityTime',
				data: 'timeId='+timeId+"&mobile="+mobile,
				dataType: 'json',
				success: function(data){
					hideLoader();
					if(data.status==200){ //抢购成功
						$("ul.custom-list li").remove();
						$("#activityDate").val(data.activityDate);
						$("#startTime").val(data.startTime);
						$("#endTime").val(data.endTime);
						var productList = data.productList;
						if(productList.length>0){
							for(var i=0; i<productList.length; i++){
								var activityProduct = productList[i];
								var product = activityProduct.product;
								var contentHtml = '<li id="'+activityProduct.cartId+'" data-icon="false">';
								contentHtml += '<a id="'+product.id+'" class="product" data-transition="slide" href="#" style="background-color: #fff; padding: .5em .5em .5em .5em;">';
								contentHtml += '<div class="product-img" style="width: 108px; height: 80px; border: none; margin: 0px; margin-right: 10px;">';
								contentHtml += '<img id="photo'+i+'" style="width: 108px; height: 80px;" class="displayImages" src="${ctxFront }/images/loading.png" path="${ctxShop}/download?filePath='+product.logoUrl+'">';
								contentHtml += '<input type="hidden" id="actProductId" value="'+activityProduct.id+'"/>';
								contentHtml += '<input type="hidden" id="number" value="'+activityProduct.number+'"/>';
								contentHtml += '<input type="hidden" id="buyNumber" value="'+activityProduct.buyNumber+'"/>';
								contentHtml += '<input type="hidden" id="price" value="'+activityProduct.price+'"/>';
								contentHtml += '<input type="hidden" id="buyState" value="'+activityProduct.buyState+'"/>';
								contentHtml += '<input type="hidden" id="cartId" value="'+activityProduct.cartId+'"/>';
								contentHtml += '</div>';
								contentHtml += '<h2 style="margin: 0em 0.8em 0.5em 107px;">'+product.name+'</h2>';
								contentHtml += '<p><label class="float-left price-color" style="font-size: 12px;">原价</label><label class="float-left price-color line_m" style="font-size: 12px;">￥'+product.price+'</label></p>';
								contentHtml += '<p><label class="float-left amount" style="font-size: 16px; line-height: 25px;"><strong>￥'+activityProduct.price+'</strong></label></p>';
								contentHtml += '<p><label class="float-left buy-desc" style="font-size: 12px;"></label></p>';
								contentHtml += '<p class="ui-li-aside" style="top: 50%; margin-top: -15px;">';
								contentHtml += '<!-- status为0则不能操作，1为可操作 -->';
								contentHtml += '<img status="0" class="buyImg" src="${ctxFront }/images/business/btn_4.png" width="56" height="30" onclick="doBuyProduct(this)" />';
								contentHtml += '</p>';
								contentHtml += '</a>';
								contentHtml += '</li>';
								$(".custom-list").append(contentHtml);
							}
						}else{
							var contentHtml = '<li data-icon="false" style="text-align: center;">';
							contentHtml += '暂无抢购商品.';
							contentHtml += '</li>';
							$("ul.custom-list").append(contentHtml);
						}
						$("ul.custom-list").listview('refresh'); // 刷新listview控件
						//预加载图片
						startLoadImage();
						//全部处理完成开启定时器
						//处理时间定时器时间元素索引
						timer = setInterval("activityTimer()",1000);//1000为1秒钟
					}else{
						openPopup(data.message);
						closePopup(2000);
					}
				},
				failure: function(){
					openPopup("操作失败");
					closePopup(2000);
				}				
			});
			
		}
	</script>
	<script type="text/javascript">
		//定时器更新抢购活动时间
		var timer = setInterval("activityTimer()",1000);//1000为1秒钟
		function activityTimer(){
			var activityDate = $("#activityDate").val();
			var startTime = $("#startTime").val();
			var endTime = $("#endTime").val();
			var nowDate = new Date();
	        var year = nowDate.getFullYear();       //年
	        var month = nowDate.getMonth() + 1;     //月
	        var day = nowDate.getDate();            //日
	        var startDate = new Date((activityDate+" "+startTime).replace(/\-/g, "\/"));
	        var endDate = new Date((activityDate+" "+endTime).replace(/\-/g, "\/"));
	        if(nowDate<startDate){ //时间活动还未开始
	        	$(".time-title").text("距离本场开始");
	        	var time=(startDate.getTime()-nowDate.getTime());//毫秒
				reckonTime(time);
				//alert("距离开始："+$(".hours").text()+"小时"+$(".minutes").text()+"分钟"+$(".seconds").text()+"秒");
	        	//处理抢购图片状态
        		$(".TabContent").find(".buyImg").each(function(){
        			$(this).attr("status", 0);
        			$(this).attr("src", "${ctxFront }/images/business/btn_4.png");
        			$(this).parent().parent().find(".buy-desc").text(startTime+"准时开抢").css("color", "green");
        		});
	        }else{
	        	if(nowDate>=startDate && nowDate<endDate){
	        		$(".time-title").text("距离本场结束");
	        		var time=(endDate.getTime()-nowDate.getTime());//毫秒
					reckonTime(time);
					//alert("距离结束："+$(".hours").text()+"小时"+$(".minutes").text()+"分钟"+$(".seconds").text()+"秒");
	        		//处理抢购图片状态
	        		$(".TabContent").find(".product").each(function(){
	        			var number = $(this).find("input[id='number']").val();
	        			var buyNumber = $(this).find("input[id='buyNumber']").val();
	        			var buyState = $(this).find("input[id='buyState']").val();
	        			var bl =  (Math.round(parseInt(buyNumber) / parseInt(number) * 10000) / 100.00 + "%");
	        			$(this).find(".buy-desc").text("已抢购"+bl).css("color", "#bbb");
	        			if(buyState=="1"){ //已抢购
	        				$(this).find(".buyImg").attr("status", 0);
	        				$(this).find(".buyImg").attr("src", "${ctxFront }/images/business/btn_5.png");
	        			}else{
	        				if(parseInt(buyNumber)>=parseInt(number)){ //抢光了
	        					$(this).find(".buyImg").attr("status", 0);
	        					$(this).find(".buyImg").attr("src", "${ctxFront }/images/business/btn_2.png");
	        				}else{
	        					$(this).find(".buyImg").attr("status", 1);
	        					$(this).find(".buyImg").attr("src", "${ctxFront }/images/business/btn_3.png");
	        				}
	        			}
	        		});
	        	}else{
	        		clearInterval(timer);
	        		$(".time-title").text("本场活动结束");
	        		$(".hours").text("00");
	        		$(".minutes").text("00");
	        		$(".seconds").text("00");
	        		//处理抢购图片状态
	        		$(".TabContent").find(".buyImg").each(function(){
	        			$(this).attr("status", 0);
	        			$(this).attr("src", "${ctxFront }/images/business/btn_1.png");
	        			$(this).parent().parent().find(".buy-desc").text("已结束.").css("color", "green");
	        		});
	        	}
	        }
	        
		}
		function reckonTime(time){
			var hours=(time/(1000*60*60));
			hours = parseInt(hours);
			$(".hours").text(hours<10?0+""+hours:hours);
			time=time-hours*(1000*60*60);
			var minutes = time/(1000*60);
			minutes = parseInt(minutes);
			$(".minutes").text(minutes<10?0+""+minutes:minutes);
			time=time-minutes*(1000*60);
			var seconds = time/1000;
			seconds = parseInt(seconds);
			$(".seconds").text(seconds<10?0+""+seconds:seconds);
		}
		
		function showShoppingCart(){
			//验证是否登录
			if(!checkLogin()) return;
			
			loading('正在跳转，请稍等...');
			setTimeout(function(){
				hideLoader();
				document.location="${ctxShop}/shoppingcart?sid="+sid+"&mobile="+mobile+"&classifyId=&shopModel=&activity=${activity.id}&appId="+appId;				
			},1000);
		}
	</script>
	<script type="text/javascript"> 
	function iEventGetNavgitionInfo(){
		var result = {
			title:"${activity.name }",
		    leftBtn:{ 
		    	type:0,	//0只显示返回,1只显示关闭，2显示返回，关闭
				backFun:"iEventGoBack()"   //返回执行的事件，不带的话由iOS控制。
			}            
		};
		if($global_isAndroid){
			window.control.onJsComplete(JSON.stringify(result));
			return;
		}
		return JSON.stringify(result);
	}
	function iEventGoBack(){
		document.location="ievent://quitWebView";
	}
	</script>
</head>
<body data-role="page" style="background-color: #fff;">
	<div role="main" class="ui-content" style="padding: 0px; margin-top: 55px;">
		<div id="popup" data-role="popup" data-position-to="window" data-overlay-theme="a" data-theme="b" class="ui-content">
		  <p></p>
		</div>
		<%@include file="/WEB-INF/views/mobile/layouts/checkLoginPopup.jsp" %>
		<div class="container">
			<div class="TabMenu">
				<div class="allMenu">			
				<c:forEach items="${activity.timeList}" var="aTime" varStatus="vs">
				<span>
					<input type="hidden" id="timeId" value="${aTime.id }"/>
					<label class="color-huise tab-time">${aTime.startTime }</label>
					<label class="color-huise tab-title" style="font-size: 12px;"><fmt:formatDate value="${aTime.activityDate }" pattern="M月d日"/></label>
				</span>
				</c:forEach>
				</div>
			</div>
			<div class="ContentFrame">
				<!-- <div class="AllTabs"> -->
					<div class="TabContent">
						<input type="hidden" id="activityDate" value="<fmt:formatDate value="${activityTime.activityDate }" pattern="yyyy-MM-dd"/>" />
						<input type="hidden" id="startTime" value="${activityTime.startTime }" />
						<input type="hidden" id="endTime" value="${activityTime.endTime }" />
						<div class="activityTime-title">
							<div class="float-left" align="left" style="width: 45%;"><label class="float-left" style="font-size: 14px; color: #B0B0B0; margin-left: 0px; font-weight: 900;">▕</label><label class="float-left" style="font-size: 14px; color: #dd4814; margin-left: 2px;">限时限量&nbsp;疯狂抢购</label></div>
							<div class="float-left color-huise" style="width: 55%;">
								<table border="0" cellpadding="0" cellspacing="0" height="100%" style="float: right; margin-right: 10px;">
									<tr>
										<td valign="middle" class="color-huise time-title" style="font-size: 14px;">距离本场开始</td>
										<td width="20"><label class="color-huise min-time hours" style="font-size: 14px;">00</label></td>
										<td valign="middle" class="color-huise">:</td>
										<td width="20"><label class="color-huise min-time minutes" style="font-size: 14px;">00</label></td>
										<td valign="middle" class="color-huise">:</td>
										<td width="20"><label class="color-huise min-time seconds" style="font-size: 14px;">00</label></td>
									</tr>
								</table>
							</div>
						</div>
						<div class="custom-module">
						<ul data-role="listview" class="custom-list">
						<c:if test="${fn:length(activityTime.productList)>0}">
						<c:forEach items="${activityTime.productList}" var="activityProduct" varStatus="vs">
							<c:set var="product" value="${activityProduct.product}" scope="request" />
							<li id="${product.cartId }" data-icon="false">
								<a id="${product.id }" class="product" data-transition="slide" href="#" style="background-color: #fff; padding: .5em .5em .5em .5em;">
								    <div class="product-img" style="width: 108px; height: 80px; border: none; margin: 0px; margin-right: 10px;">
								    	<img id="photo${vs.index }" style="width: 108px; height: 80px;" class="displayImages" src="${ctxFront }/images/loading.png" path="${ctxShop}/download?filePath=${product.logoUrl }">
								    	<input type="hidden" id="actProductId" value="${activityProduct.id }"/>
								    	<input type="hidden" id="number" value="${activityProduct.number }"/>
								    	<input type="hidden" id="buyNumber" value="${activityProduct.buyNumber }"/>
								    	<input type="hidden" id="price" value="${activityProduct.price }"/>
								    	<input type="hidden" id="buyState" value="${activityProduct.buyState }"/>
								    	<input type="hidden" id="cartId" value="${activityProduct.cartId }"/>
								    </div>
								    <h2 style="margin: 0em 0.8em 0.5em 107px;">${product.name}</h2>
								    <p><label class="float-left price-color" style="font-size: 12px;">原价</label><label class="float-left price-color line_m" style="font-size: 12px;">￥${product.price }</label></p>
								    <p><label class="float-left amount" style="font-size: 16px; line-height: 25px;"><strong>￥${activityProduct.price }</strong></label></p>
							        <p><label class="float-left buy-desc" style="font-size: 12px;"></label></p>
							        <p class="ui-li-aside" style="top: 50%; margin-top: -15px;">
							        	<!-- status为0则不能操作，1为可操作 -->
							        	<img status="0" class="buyImg" src="${ctxFront }/images/business/btn_4.png" width="56" height="30" onclick="doBuyProduct(this)" />
							        </p>
							    </a>
						    </li>
						</c:forEach>
						</c:if>
						<c:if test="${fn:length(activityTime.productList)==0}">
							<li data-icon="false" style="text-align: center;">
								暂无抢购商品.
							</li>
						</c:if>
						</ul>
						</div>
					</div>
				<!-- </div> -->
			</div>
		</div>
	</div>
	<div data-role="footer" class="ui-footer" data-position="fixed" data-tap-toggle="false">
		<div class="float-left footer-left">
			<div class="a"><label class="float-left">总金额：</label><label class="float-left amount totalAmount"><strong>￥${totalAmount }</strong></label></div>
	    </div>
		<div class="float-right footer-right">
			<div class="b"><img alt="" src="${ctxFront }/images/shop/gwc_0.png" onclick="showShoppingCart()"></div>
			<div class="badger-css totalNumber-badger" style="${totalNumber==0?'display:none;':'' }" onclick="showShoppingCart()"><div class="badger-badge totalNumber" style="border-radius:50%">${totalNumber }</div></div>
	    </div>
	</div><!-- /footer -->
</body>
</html>